package com.longxi.tianjintianbao.ui.presenter.repair_publish;

import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataUserController;
import com.longxi.tianjintianbao.listener.SelectCommunityListener;
import com.longxi.tianjintianbao.model.Build;
import com.longxi.tianjintianbao.ui.adapter.multitype.BuildViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.repair_publish.ISelectCommunityAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 登录后小区多选
 */

public class SelectCommunityAtPresenter extends BasePresenter<ISelectCommunityAtView> {

    private MultiTypeAdapter adapter;
    private Items items;
    private List<String> buildids = new ArrayList<>();
    private List<String> builds = new ArrayList<>();
    private String buildid = "";
    private String build = "";

    public SelectCommunityAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        mContext.setTitle("选择楼盘");
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setTvRight("保存");
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(Build.class, new BuildViewBinder(selectCommunityListener));
            getView().getRvContent().setAdapter(adapter);
        }
    }

    private void showSureBtn(int position) {
        adapter.notifyItemChanged(position);
    }

    public void getCommunity(){
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getUserBuild(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<Build>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                MyUtils.showToast(throwable.message);
                mContext.showError();
            }

            @Override
            public void onNext(HttpResult<Build> result) {
                if(result.getData() != null && result.getData().size() > 0){
                    String buildid = MyApplication.loginUser.buildid;
                    List<String> buildidList= Arrays.asList(buildid.replace(" ", "").split(","));

                    try {
                        for (Build build : result.getData()) {
                            for (String s : buildidList) {
                                if(build.getBuildid() == Integer.parseInt(s)){
                                    build.setSelect(true);
                                    buildids.add(String.valueOf(build.getBuildid()));
                                    builds.add(build.getBuild());
                                }
                            }
                        }
                    }catch (Exception e) {
                        
                    }
                }

                items = NListRefresh.getInstance().fjData(result,
                        getView().getRefreshLayout(),
                        items,
                        adapter,
                        mContext);
            }
        });
    }

    /**
     * 保存用户选择的小区
     */
    public void saveUserBuild() {
        if(buildids.size() == 0) {
            MyUtils.showToast("请选择小区");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            String str = buildids.toString();
            buildid = str.substring(1, str.length() - 1).replace(" ", "");
            String str2 = builds.toString();
            build = str2.substring(1, str2.length() - 1).replace(" ", "");
            object.put("buildid", buildid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().saveUserBuild(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }

                MyUtils.showToast("保存成功");

                MyApplication.loginUser.setBuildid(buildid);
                MyApplication.loginUser.setBuild(build);
                DataUserController.updateUser(MyApplication.loginUser);

                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    SelectCommunityListener selectCommunityListener = new SelectCommunityListener() {
        @Override
        public void onRemove(Build build, int position) {
            buildids.remove(build.getBuildid() + "");
            builds.remove(build.getBuild());
            showSureBtn(position);
        }

        @Override
        public void onAdd(Build build, int position) {
            buildids.add(build.getBuildid() + "");
            builds.add(build.getBuild());
            showSureBtn(position);
        }
    };

    public void onDestroy() {
        selectCommunityListener = null;
    }
}
